// import { ftCreate, ftUpdate } from '@/service/modules/tag';
import { ftUpload } from '@/service/modules/normon';
import { getLocalStorage } from '@/utils/local';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { Form, GetProp, Input, message, Modal, Upload, UploadProps } from 'antd';
import md5 from 'crypto-js/md5';
import { forwardRef, memo, useEffect, useImperativeHandle, useState } from 'react';
import { useModel } from 'umi';

type Iprops = {
  onClose: (refresh?: boolean) => void;
  open: boolean;
  title: string;
  data: any;
};
type FormValues = {
  id?: string;
  name: string;
  password: string;
  telPhone: string;
  avatar: string;
};

export interface IAddOrUpdateRef {
  init: () => void;
}

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

const getBase64 = (img: FileType, callback: (url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
};

const beforeUpload = (file: FileType) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('图片格式为JPG/PNG');
  }
  const isLt2M = file.size / 1024 / 1024 < 1;
  if (!isLt2M) {
    message.error('图片不能大于1m');
  }
  return isJpgOrPng && isLt2M;
};

const AddOrUpdate = (props: Iprops, ref: React.Ref<IAddOrUpdateRef>) => {
  const { onClose, open, title, data } = props;
  const [form] = Form.useForm<FormValues>();
  const { createAction, updateAction } = useModel('usersModel');
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();
  async function onOk() {
    // 检查form数据
    await form.validateFields();

    const from = form.getFieldsValue(['id', 'name', 'password', 'telPhone', 'avatar']);

    const { id, name, password, telPhone, avatar } = from;
    // 对密码进行 MD5 加密
    const encryptedPassword = md5(password).toString();
    let res = null;
    if (!id) {
      res = await createAction(
        {
          name,
          password: encryptedPassword,
          telPhone,
          avatar,
        },
        true,
      );
    } else {
      res = await updateAction(
        {
          id,
          name,
          telPhone,
          avatar,
        },
        true,
      );
    }
    const { code } = res;
    if (code === 200) {
      message.success('操作成功');
      onCancel();
    }
  }
  function onCancel() {
    form.resetFields();
    setImageUrl('');
    onClose();
  }

  const handleChange: UploadProps['onChange'] = (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj as FileType, (url) => {
        setLoading(false);
        setImageUrl(url);
        form.setFieldValue('avatar', url);
      });
    }
  };
  const uploadButton = (
    <button style={{ border: 0, background: 'none' }} type="button">
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </button>
  );

  useEffect(() => {
    if (!data) return;
    const { id, name, password, telPhone, avatar = '' } = data;

    setImageUrl(avatar);
    form.setFieldsValue({
      id,
      name,
      password,
      telPhone,
      avatar,
    });
  }, [data]);

  useImperativeHandle(ref, () => {
    return {
      init() {
        console.log('use的方法被使用');
      },
    };
  });

  return (
    <Modal
      title={title}
      closable={{ 'aria-label': 'Custom Close Button' }}
      open={open}
      onOk={onOk}
      onCancel={onCancel}
    >
      <Form form={form} name="demo_form" layout="vertical">
        <Form.Item label="账号" name="name" rules={[{ required: true, message: '请输入账号!' }]}>
          <Input placeholder="请输入账号" />
        </Form.Item>
        {!data ? (
          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: '请输入密码!' }]}
          >
            <Input.Password placeholder="请输入密码" />
          </Form.Item>
        ) : null}

        <Form.Item
          label="手机号"
          name="telPhone"
          rules={[{ required: true, message: '请输入手机号!' }]}
        >
          <Input placeholder="请输入手机号" />
        </Form.Item>

        <Form.Item label="头像" name="avatar" rules={[{ required: true, message: '请上传头像!' }]}>
          <Upload
            name="file"
            listType="picture-card"
            className="avatar-uploader"
            showUploadList={false}
            action={ftUpload}
            headers={{ Authorization: `Bearer ${getLocalStorage('token')}` }}
            beforeUpload={beforeUpload}
            onChange={handleChange}
          >
            {imageUrl ? (
              <img src={imageUrl} alt="avatar" style={{ width: '100%' }} />
            ) : (
              uploadButton
            )}
          </Upload>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default memo(forwardRef(AddOrUpdate));
